import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:spring_fairy/api/api.dart';
import 'package:spring_fairy/api/diary_api.dart';
import 'package:spring_fairy/api/mood_type_api.dart';
import 'package:spring_fairy/api/point_image_api.dart';
import 'package:spring_fairy/model/mood_diary.dart';
import 'package:spring_fairy/model/mood_point_image.dart';
import 'package:spring_fairy/model/mood_track.dart';
import 'package:spring_fairy/model/mood_track_point.dart';
import 'package:spring_fairy/model/mood_type.dart';
import 'package:spring_fairy/util/get_current_position.dart';
import 'package:spring_fairy/util/get_current_weather.dart';
import 'package:spring_fairy/widget/weather_card.dart';
import 'package:table_calendar/table_calendar.dart';
import '../api/mood_track_api.dart';

///存储用户的心情、轨迹、标记点、日记等信息
@pragma('vm:entry-point')
class Store {
  Store._();

  static Set<MoodTrackPoint> _list = {};

  static List<MoodType> _moodTypes = [];

  static MoodTrack? currentMoodTrack;

  static Map<MoodTrackPoint,List<MoodPointImage>> _images = {};

  static Map<MoodTrack,List<MoodTrackPoint>> _history = {};

  static MoodTrack? RecordLastMoodTrack;

  static List<MoodDiary> diarys = [];

  static MoodTypeAPI _moodTypeAPI = MoodTypeAPI();
  static MoodTrackAPI _moodTrackAPI = MoodTrackAPI();
  static PointImageAPI _pointImageAPI = PointImageAPI();
  static DiaryAPI _diaryAPI = DiaryAPI();
  static WeatherData? weatherData;

  static bool hasLoad = false;
  static MoodDiary? currentMoodDiary;

  ///当天的日记
  static late MoodDiary _moodDiary;

  static void addMoodTrackPoint(MoodTrackPoint point) {
    _list.add(point);
  }

  static Set<MoodTrackPoint> getPoints() {
    return _list;
  }

  ///获取当天的Diary
  static MoodDiary getCurrentMoodDiary() {
    return _moodDiary;
  }

  static void setCurrentMoodDiary(MoodDiary moodDiary) {
    _moodDiary = moodDiary;
  }

  ///用户所有心情类型
  static List<MoodType> moodTypes() {
   return _moodTypes;
  }

  static void setMoodTypes(List<MoodType> moodTypes) {
    _moodTypes = moodTypes;
  }

  ///添加心情类型
  static void addMoodType(MoodType moodType) {
    _moodTypes.add(moodType);
  }

  static void deleteMoodType(MoodType moodType) {
    _moodTypes.remove(moodType);
  }


  static Future<void> loadData() async {
    getCurrentPosition().then((position) {
      getCurrentWeather(position).then((data) {
        Store.weatherData = data;
      });
    });
    await _createNewMoodTrack();
    //获取心情类型
    List<MoodType>? moodTypes = await _moodTypeAPI.getAllMoodTypes();
    if(moodTypes != null) {
      _moodTypes.addAll(moodTypes);
    }

    //获取标记点
    List<MoodTrackPoint>? points = await _moodTrackAPI.getPointsByTrack(currentMoodTrack!.id!);
    if(points == null) {
      return ;
    }

    _list.addAll(points);
    for(MoodTrackPoint point in points) {
      var images = await _getNetworkPointImages(point);
      if(images != null) {
        _images[point] = images;
      }
    }
    await refreshHistory();
    hasLoad = true;

    FlutterBackgroundService().invoke("setData",{"moodTypes":_moodTypes,"trackId":currentMoodTrack!.id!,"token":API.token,"points":points});
  }

  static List<MoodPointImage>? getPointImages(MoodTrackPoint point) {
    return _images[point];
  }

  static Future<void> _createNewMoodTrack() async {
    if(Store.currentMoodTrack == null) {
      MoodTrackAPI moodTrackAPI = MoodTrackAPI();
      MoodTrack moodTrack = MoodTrack();
      var now = DateTime.now();
      moodTrack.createdAt = now;
      moodTrack.trackDate = now;
      moodTrack.title = "${now.year}-${now.month}-${now.day}轨迹";
      var ele = await moodTrackAPI.createTrack(moodTrack);
      if (ele != null) {
        Store.currentMoodTrack = ele;
      }
    }
  }

  static void addPointImages(MoodTrackPoint point,List<MoodPointImage> images) {
    if(_images[point] == null) {
      _images[point] = images;
    } else {
      _images[point]!.addAll(images);
    }
  }

  static Future<List<MoodPointImage>?> _getNetworkPointImages(MoodTrackPoint point)  {
    return  _pointImageAPI.getAllPointImage(point.id!);
  }

  static void deletePoint(MoodTrackPoint point) {
    _list.remove(point);
    _images.remove(point);
  }

  static Map<MoodTrack,List<MoodTrackPoint>> history() {
    return _history;
  }

  static Future<void> refreshHistory() async {
    _history.clear();
    List<MoodTrack>? tracks = await _moodTrackAPI.getAllTrack();
    if(tracks != null) {
      for(MoodTrack track in tracks) {
        if(track.id == currentMoodTrack!.id) {
          continue;
        }
        List<MoodTrackPoint>? points = await _moodTrackAPI.getPointsByTrack(track.id!);
        if(points == null) {
          continue;
        }
        _history[track] = points;
        for(var point in points) {
          var images = await _getNetworkPointImages(point);
          if(images != null) {
            _images[point] = images;
          }
        }
      }
    }
  }

  static Future<void> refreshPoints() async {
    _list.clear();
    _history.remove(currentMoodTrack);

    var points = await _moodTrackAPI.getPointsByTrack(currentMoodTrack!.id!);
    if(points != null) {
      _list.addAll(points);
      _history[currentMoodTrack!] = points;
    }
  }

  Future<void> getAllMoodDiary() async {
    var list = await _diaryAPI.getAllDiary();
    diarys.addAll(list);

    var now = DateTime.now();
    for(var diary in diarys) {
      if(isSameDay(diary.createdAt, now)) {
        currentMoodDiary = diary;
      }
    }

  }

}